from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout,QSpacerItem, QSizePolicy,QHBoxLayout,QLabel
from PyQt5.QtGui import QPainter, QColor, QPen
from PyQt5.QtCore import Qt, QPointF, QTimer
import sys
import chhol,cc9d
import soil_moisture

class CurveWidget(QWidget):
    _receiveCB = {}        
    def __init__(self):
        super().__init__()
        self.chhol = chhol.Chhol(port='COM54', recvPkgCB=self._receivePkg)        
        # 设置定时器
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.chhol.receiveOnce)
        self.timer.start(20)  # 每20毫秒调用一次        
        self.initUI()      
        # 建立一个字典，端口和节点作为键，对应一个接收处理函数
        self._receiveCB[(1,32,32)] = self._handleVoltagePkg
        self._receiveCB[(2,32,32)] = self._handleVoltagePkg
        self._receiveCB[(4,32,32)] = self._handleVoltagePkg

    def _receivePkg(self, pkg: cc9d.sCc9dPkg):
        # 从包中提取端口和节点地址
        # 如果在字典中找到了对应的处理函数，则调用它
        # 如果没有找到，则打印一个警告
        key = (pkg.remote_addr, pkg.from_port, pkg.to_port)
        if key in self._receiveCB:
            self._receiveCB[key](pkg)
        else:
            print(f"没有找到处理函数: {pkg}")    
    
    def _handleVoltagePkg(self, pkg: cc9d.sCc9dPkg):
        # 如果是节点 1,2,4 的电压包
        if pkg.remote_addr not in [1,2,4]:
            return
        i = pkg.remote_addr
        adc_value = pkg.datas[0]+pkg.datas[1]*256
        voltage = adc_value/4096*3.3
        self.voltageLAB[i].setText(f'现在节点{i}的电压值为：{voltage:.2f}V')

    def initUI(self): 
        self.setWindowTitle('红绿灯控制')
        self.setGeometry(100, 100, 300, 150)
        # 创建按钮
        self.RedBTN = QPushButton('红灯', self)
        self.YellowBTN = QPushButton('黄灯', self)
        self.GreenBTN = QPushButton('绿灯', self)


        mainLAYOUT = QVBoxLayout()
        # 添加一个可伸缩的空白区域，将按钮推到窗口底部
        spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        mainLAYOUT.addItem(spacer)

        self.voltageLAB = {}
        self.soil_m={}
        # 创建节点 1,2,4 的电压显示标签
        for i in [1,2,4]:
            self.voltageLAB[i] = QPushButton(f'现在节点{i}的电压值为：<未知>', self)            
            self.soil_m[i] = soil_moisture.soil_moisture(i,32,48)
            route = self.soil_m[i].regToChhol(self.chhol.sendPkg)
            self._receiveCB[route] = self.soil_m[i].recvPkg
            self.voltageLAB[i].clicked.connect(lambda _,i=i:self.soil_m[i].read_soil_moisture())
            mainLAYOUT.addWidget( self.voltageLAB[i])
        
        # 创建水平布局并添加按钮
        buttonLAYOUT = QHBoxLayout()
        buttonLAYOUT.addWidget(self.RedBTN)
        buttonLAYOUT.addWidget(self.YellowBTN)
        buttonLAYOUT.addWidget(self.GreenBTN)        
        # 将水平布局添加到主垂直布局的底部
        mainLAYOUT.addLayout(buttonLAYOUT)
        # 设置窗口的主布局
        self.setLayout(mainLAYOUT)
        # 连接按钮的点击信号到槽函数
        self.RedBTN.clicked.connect(lambda:self.sendLedCtrlPkg(1,"红"))
        self.YellowBTN.clicked.connect(lambda:self.sendLedCtrlPkg(2,"黄"))
        self.GreenBTN.clicked.connect(lambda:self.sendLedCtrlPkg(3,"绿"))
        
    def sendLedCtrlPkg(self, ledColor:int, ledName:str):
        # 创建一个包
        pkg = cc9d.sCc9dPkg(32,16,0x0002,[ledColor])
        pkg.desc = f"点亮{ledName}灯"
        # 发送这个包
        self.chhol.sendPkg(pkg)
        print(f"发送一个包: {pkg}")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = CurveWidget()
    window.show()
    sys.exit(app.exec_())